package com.xiamo.job;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiamo.entity.EarthquakeEvent;
import com.xiamo.entity.WxPushLog;
import com.xiamo.entity.WxUser;
import com.xiamo.security.SecurityService;
import com.xiamo.service.IEarthquakeEventService;
import com.xiamo.service.IWxPushLogService;
import com.xiamo.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description:  震情预警推送
 * @return:
 * @Author: dawu
 * @Date: 2024-04-17 17:50
 */
@Component
@Slf4j
public class EarpushJob {
    @Autowired
    private SecurityService securityService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IWxPushLogService wxPushLogService;

    @Autowired
    private IEarthquakeEventService earthquakeEventService;

    @Autowired
    private RestTemplate restTemplate;


    @Scheduled(cron = "* * * * * *") //
    public void scheduledTask() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy年MM月dd日");

        Date currentTime = new Date();
        String formattedTime = sdf.format(currentTime);
        String formattedTimes = sdfs.format(currentTime);
        RestTemplate restTemplate = new RestTemplate();

        List<WxUser> wxUserList = wxUserService.list(Wrappers.<WxUser>lambdaQuery()
                .eq(WxUser::getEarPush, 1));

        String response = restTemplate.getForObject("https://api.wolfx.jp/fj_eew.json", String.class);
        JSONObject jsonObject = new JSONObject(response);

        //查询数据库根据event_id查询
        //{"EventID": "20240417091710_4", "ReportTime": "2024-04-17 17:18:38", "ReportNum": 4, "OriginTime": "2024-04-17 17:17:09",
        //"HypoCenter": "̨", "Latitude": 23.9, "Longitude": 121.81, "Magunitude": 4.8, "isFinal": true}
        EarthquakeEvent event = earthquakeEventService.getOne(Wrappers.<EarthquakeEvent>lambdaQuery()
        .eq(EarthquakeEvent::getEventID,jsonObject.getStr("EventID")));
        if(event == null){
            //进行推送插入数据库
            EarthquakeEvent events =new EarthquakeEvent();
            events.setEventID(jsonObject.getStr("EventID"));
            events.setReportTime(jsonObject.getDate("ReportTime"));
            events.setReportNum(jsonObject.getInt("ReportNum"));
            events.setOriginTime(jsonObject.getDate("OriginTime"));
            events.setHypoCenter(jsonObject.getStr("HypoCenter"));
            events.setLatitude(Double.parseDouble(jsonObject.getStr("Latitude")));
            events.setLongitude(Double.parseDouble(jsonObject.getStr("Longitude")));
            events.setMagnitude(Double.parseDouble(jsonObject.getStr("Magunitude")));
            events.setFinal(jsonObject.getBool("isFinal"));
            earthquakeEventService.save(events);
            // 调用 securityService 中的方法

            String accessToken = securityService.getToken();
            for (WxUser wxUser : wxUserList) {
                String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;

                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json");

                String jsonBody = "{\n" +
                        "    \"touser\": \"" +wxUser.getOpenId()+ "\",\n" +
                        "    \"template_id\": \"-hw11A9slgtJXyh_xurAdtTsxigtw5-KswsUa6RAJVg\",\n" +
                        "    \"page\": \"pages/index/index\",\n" +
                        "    \"miniprogram_state\": \"formal\",\n" +//正式版本
                        "    \"lang\": \"zh_CN\",\n" +
                        "    \"data\": {\n" +
                        "        \"date1\": {\n" +
                        "            \"value\": \"" + events.getOriginTime() + "\"\n" +
                        "        },\n" +
                        "        \"character_string2\": {\n" +
                        "            \"value\": \"" + events.getMagnitude()+ "\"\n" +
                        "        },\n" +
                        "        \"thing3\": {\n" +
                        "            \"value\": \"" +events.getHypoCenter() + "\"\n" +
                        "        },\n" +
                        "        \"thing4\": {\n" +
                        "            \"value\": \"" +"经度"+events.getLongitude()+",纬度"+events.getLatitude() + "\"\n" +
                        "        }\n" +
                        "    }\n" +
                        "}";

                HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

                ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

                WxPushLog wxPushLog = new WxPushLog();
                wxPushLog.setTemplateId("-hw11A9slgtJXyh_xurAdtTsxigtw5-KswsUa6RAJVg");
                wxPushLog.setCreateTime(new Date());
                wxPushLog.setTouser(wxUser.getOpenId());

                if (responseEntity.getStatusCode().is2xxSuccessful()) {
                    wxPushLog.setStatus("push success");
                    log.info("订阅消息发送成功");
                } else {
                    wxPushLog.setStatus("push fail");
                    log.error("订阅消息发送失败");
                }
                wxPushLogService.save(wxPushLog);
            }

        }


    }
}
